<style lang="less">
  @import '../../styles/common.less';
  @import '../../tables/components/table.less';
</style>

<template>
  <div>
    <Row :gutter="10">
      <Card>
        <div class="table-head">
          <!--<Button type="primary" class="Button" @click="ExportData()">导出数据</Button>-->
          <Button type="primary" class="Button" @click="remove()">删除</Button>
          <Button type="primary" class="Button" @click="add()">添加</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData"
                 @on-selection-change="selectionChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
      <!--详情-->
      <Drawer :closable="false" :width="DrawerWidth" v-model="showCurrentTableData" class="Drawer-body">
        <div class="Drawer_pStyle">
          <span></span>
          <span class="del" @click="hideDetailModal"><Icon type="md-close"/></span>
        </div>
        <div class="body">
          <Form label-position="top">
            <FormItem label="标题">
              <div class="dataDetail-div" v-text="dataDetail.title"></div>
            </FormItem>
            <FormItem label="创建时间">
              <div class="dataDetail-div" v-text="dataDetail.create_time"></div>
            </FormItem>
            <FormItem label="部门">
              <div class="dataDetail-div" v-text="dataDetail.department ? dataDetail.department.name : ''"></div>
            </FormItem>
            <FormItem label="状态">
              <div class="dataDetail-div" v-text="dataDetail.status ? dataDetail.status.title : ''"></div>
            </FormItem>
            <FormItem label="内容">
              <div class="dataDetail-div ck-editor-content" v-html="dataDetail.content"></div>
            </FormItem>
          </Form>
        </div>
        <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
          <Button type="text" @click="hideDetailModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="release()" v-if="status == 3">发布</Button>
        </div>
      </Drawer>
      <!--编辑-->
      <Drawer :closable="false" :width="WindowWidth" v-model="addCurrentTableData" class="Drawer-body">
        <div class="Drawer_pStyle">
          <span>编辑</span>
          <span class="del" @click="hideAddModal"><Icon type="md-close"/></span>
        </div>
        <div class="body">
          <table class="add-table" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td class="left paddingTop22" valign="top" align="right">
                <Form label-position="top" class="from-content">
                  <FormItem label="">
                    <Input v-model="addData.title" placeholder="请输入标题"></Input>
                  </FormItem>
                  <FormItem label="">
                    <!--<textarea name="content" id="content"></textarea>-->
                    <div id="content" class="ck-editor-content" :style="{minHeight: WindowHeight - 252 + 'px'}"></div>
                    <!--<div id="toolbar-container"></div>
                    <div id="editor" class="editor-content"></div>-->
                  </FormItem>
                </Form>
              </td>
              <td class="right" valign="top" :style="{width: WindowWidth > 1440 ? WindowWidth*0.3 + 'px' : '288px'}">
                <Form label-position="top">
                  <FormItem label="标签">
                    <Input v-model="addData.tag" placeholder="标签"></Input>
                  </FormItem>
                  <FormItem label="选择范围">
                    <Select v-model="addData.department_id" :transfer="true" @on-change="onChangeTypeSelect"
                            style="width:100%;">
                      <Option v-for="item in department_idArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </FormItem>
                  <FormItem label="审批人">
                    <Select v-model="addData.approvers" multiple :transfer="true" style="width:100%;">
                      <Option v-for="item in approversArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </FormItem>
                </Form>
              </td>
            </tr>
          </table>
        </div>
        <div class="footer" :style="{width: WindowWidth - 32 + 'px'}">
          <Button type="text" @click="hideAddModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
        </div>
      </Drawer>
    </Row>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../../libs/util';
  import Utils from '../../../libs/mod.utils';
  import String from '../../../libs/mod.string';
  import Modal from '../../../libs/mod.Modal';
  import Ckeditor from '../../../libs/mod.ckeditor';
  export default {
    components: {},
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        id: '',
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'title',
            title: '标题',
          },
          {
            key: 'department',
            title: '部门',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.department.name)
              ]);
            }
          },
          {
            key: 'status',
            title: '状态',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.status.title)
              ]);
            }
          },
          {
            key: 'create_time',
            title: '创建时间',
            width: 160
          },
          {
            title: 'Action',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, params.index);
                    }
                  }
                }, '修改')
              ]);
            }
          }
        ],
        data: [],
        dataDetail: {},
        status: -1,//公告状态
        initTable: [],
        format: Util.constant.format,
        addCurrentTableData: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          type: 'announcement',
          title: '',
          tag: '',
          content: '',
          department_id: '',
          approvers: [],
        },
        selectionArr: [],
        departmentsObj: {},
        department_idArr: [],
        approversArr: [],
        editor: null,
        DrawerWidth: Util.constant.DrawerWidth,// 抽屉的宽度
        WindowWidth: Util.constant.WindowWidth,// 窗口的宽度
        WindowHeight: Util.constant.WindowHeight,// 窗口的高度
      };
    },
    mounted () {
      this.getData();
    },
    methods: {
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          page: _this.page,
          size: _this.size,
        };
        var params = {
          url: '/sd/announcement/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        console.log('page', page);
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.show(index, data);
      },
      show: function (index, data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/sd/announcement/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.status = _data.status ? _data.status.id : -1;
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 获取居委会列表
      getDepartments: function () {
        var _this = this;
        var data = {};
        var params = {
          url: '/department/committee',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var departmentsObj = {};
            var department_idArr = [];
            var approversArr = [];
            var id = _data.id;
            var name = _data.name;
            var approver = _data.approver;
            if (!departmentsObj[id]) {
              departmentsObj[id] = {};
            }
            departmentsObj[id].approver = approver;
            var obj = {
              id: id,
              name: name
            };
            department_idArr.push(obj);
            var children = _data.children;
            for (var k in children) {
              if (!children[k]) {
                continue;
              }
              var id = children[k].id;
              var name = children[k].name;
              var approver = children[k].approver;
              if (!departmentsObj[id]) {
                departmentsObj[id] = {};
              }
              departmentsObj[id].approver = approver;
              var obj = {
                id: id,
                name: name
              };
              department_idArr.push(obj);
            }
            _this.departmentsObj = departmentsObj;
            _this.department_idArr = department_idArr;
            _this.approversArr = approversArr;
            _this.onChangeTypeSelect(_this.addData.department_id);
          } else {
            _this.$Message.error('查询居委会信息失败!');
          }
        }
      },
      // 选中居委会
      onChangeTypeSelect: function (_id) {
        var _this = this;
        var id = _id;
        if (!(id && id != '')) {
          return false;
        }
        var departmentsObj = _this.departmentsObj;
        var approversArr = departmentsObj[id] ? departmentsObj[id].approver : [];
        _this.approversArr = approversArr;
        _this.addData.approvers = [];
        if (approversArr.length == 0) {
          _this.$Message.error('所选居委会暂无审批人，请选择其他居委会!');
        }
      },
      // 富文本
      initCkeditor () {
        var _this = this;
        Ckeditor.initCkeditor(_this, 'content', function (editor) {
          _this.editor = editor;
          _this.editor.setData(_this.addData.content);
        });
      },
      // 隐藏详情页面
      hideDetailModal: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      // 选中文件
      handleUpload: function (file) {
        var _this = this;
        _this.UploadFile(file);
        return false;
      },
      // 上传文件
      UploadFile: function (file) {
        var _this = this;
        var name = file.name;
        var arr = name.split('.');
        var type = arr[arr.length - 1];
        if (!(Util.constant.format.indexOf(type) > -1)) {
          _this.$Message.error('请上传图片!');
          return false;
        }
        var formData = new FormData();
        formData.append("file", file);
        formData.append("type", "image");
        var params = {
          url: '/file/addFile',
          type: Util.method.post,
          data: formData,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            var id = data.id;
            var name = data.name;
            var url = data.url;
            var obj = {
              id: id,
              name: name,
              url: url,
            };
            _this.addData.accessory.push(obj);
          } else {
            _this.$Message.error('上传失败!');
          }
        }
      },
      // 删除附件
      delAccessory: function (el) {
        var _this = this;
        var id = el.id;
        var accessory = _this.addData.accessory;
        for (var k in accessory) {
          if (!accessory[k]) {
            continue;
          }
          if (id == accessory[k].id) {
            var del = accessory.splice(k, 1);
            break;
          }
        }
        _this.addData.accessory = accessory;
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        var title = _this.addData.title;
        var content = _this.editor ? _this.editor.getData() : '';
        if (title == '' && (content == '' || content == '<p>&nbsp;</p>')) {
          _this.addCurrentTableData = false;
        } else {
          Modal.confirm(_this, {content: '取消编辑内容将丢失，请确认？'}, function () {
            _this.addCurrentTableData = false;
            if (_this.editor) {
              _this.editor.setData('');
            }
          }, function () {
          });
        }
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.addData.title = '';
        _this.addData.tag = '';
        _this.addData.content = '';
        _this.addData.department_id = '';
        _this.addData.approvers = [];
        _this.getDepartments();
        if (!_this.editor) {
          _this.initCkeditor();
        } else {
          _this.editor.setData('');
        }
        _this.ajaxType = 'add';
        _this.addCurrentTableData = true;
      },
      // 保存数据
      save: function () {
        var _this = this;
        var title = _this.addData.title;
        var tag = _this.addData.tag;
//        var content = _this.addData.content;
        var content = _this.editor ? _this.editor.getData() : '';
        var department_id = _this.addData.department_id;
        var approvers = _this.addData.approvers;
        if (!(title && title != '')) {
          _this.$Message.error('请填写标题!');
          return false;
        }
        if (department_id == '') {
          _this.$Message.error('请选择范围!');
          return false;
        }
        if (approvers.length == 0) {
          _this.$Message.error('请选择审批人!');
          return false;
        }
        if (!(content && content != '')) {
          _this.$Message.error('请填写内容!');
          return false;
        }
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: _this.addData.type,//'announcement',
          title: title,
          content: content,
          tag: tag,
          department_id: department_id,
          approvers: approvers,
        };
        var url = '/sd/announcement/add';
        if (_this.ajaxType == 'update') {
          url = '/sd/announcement/update';
        }
        var params = {
          url: url,
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addCurrentTableData = false;
            _this.addData.title = '';
            _this.addData.tag = '';
            _this.addData.content = '';
            _this.addData.department_id = '';
            _this.addData.approvers = [];
            if (_this.editor) {
              _this.editor.setData('');
            }
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 显示修改界面
      update: function (data, index) {
        var _this = this;
        _this.ajaxType = 'update';
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/sd/announcement/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.addData.title = _data.title;
            _this.addData.tag = _data.tag;
            _this.addData.content = _data.content;
            _this.addData.department_id = _data.department ? _data.department.id : '';
            var approver = _data.approver || [];
            var approvers = [];
            for (var i in approver) {
              if (!approver[i]) {
                continue;
              }
              var id = approver[i].id;
              approvers.push(id);
            }
            _this.addData.approvers = approvers;
            _this.getDepartments();
            if (!_this.editor) {
              _this.initCkeditor();
            } else {
              _this.editor.setData(_this.addData.content);
            }
            _this.addCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 发布
      release: function () {
        var _this = this;
        var data = {
          type: 'status',
          id: _this.id,
          status: 5
        };
        var params = {
          url: '/sd/announcement/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.error('请填选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/sd/announcement/deleteMultiple',
            type: Util.method.get,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var fields = [
          {
            field: 'id',
            title: '#',
            type: 'int',
            order: 1,
          },
          {
            field: 'name',
            title: '姓名',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'anonymous',
            title: '是否匿名',
            type: 'varchar',
            order: 3,
          },
          {
            field: 'content',
            title: '内容',
            type: 'varchar',
            order: 4,
          },
          {
            field: 'create_time',
            title: '时间',
            type: 'datetime',
            order: 5,
          },
        ];
        var fieldsStr = Util.toStr(fields);
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'app-suggest',
          fields: fieldsStr,
        };
        var params = {
          url: '/file/db2excle',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            Utils.DownloadFile(url, '导出社区公告_' + date + '.xlsx');
          } else {
            _this.$Message.error('导出信息失败!');
          }
        }
      },
    }
  };
</script>
